import { objectToString } from '@/common/utils'
import Taro from '@tarojs/taro'

const tools = {
  /**
   * 网络请求
   */
  request: opts => {
    const {
      url = '',
      params = {},
      method = 'GET',
      ...rest // 剩余参数
    } = opts
    return new Promise((resolve, reject) => {
      Taro.request({ url, data: params, method, ...rest })
        .then(res => {
          const { data } = res
          if (data?.code === 1) {
            // 成功
            resolve(data)
          } else {
            // 失败
            reject(res)
          }
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  /**
   * 页面loading
   */
  showLoading: (param = '') => {
    let dptOpts = {
      title: '加载中...',
      mask: true // 防止触摸穿透
    }
    if (Object.prototype.toString.call(param) === '[object String]') {
      dptOpts.title = param
    } else if (Object.prototype.toString.call(param) === '[object Object]') {
      dptOpts = {
        ...dptOpts,
        ...param
      }
    }
    return Taro.showLoading(dptOpts)
  },
  hideLoading: () => {
    Taro.hideLoading()
  },
  /**
   * 页面提示
   */
  showToast: param => {
    let dptOpts = {
      title: '温馨提示', // 提示内容
      icon: 'none',
      mask: true,
      duration: 2000 // 提示时间
    }
    if (Object.prototype.toString.call(param) === '[object String]') {
      dptOpts.title = param
    } else if (Object.prototype.toString.call(param) === '[object Object]') {
      dptOpts = {
        ...dptOpts,
        ...param
      }
    } else {
      throw new Error('参数类型有误，应该是字符串或者对象')
    }
    return Taro.showToast(dptOpts)
  },
  /**
   *
   * @{param}	 url 页面路径
   * @{Object}	 data 页面参数
   */
  navigateTo: ({ url, data }) => {
    const searchStr = objectToString(data)
    return Taro.navigateTo({
      url: `${url}?${searchStr}`
    })
  },
  isAliPay: Taro.ENV_TYPE.ALIPAY === Taro.getEnv(),
  isBaiDu: Taro.ENV_TYPE.SWAN === Taro.getEnv(),
  isH5: Taro.ENV_TYPE.WEB === Taro.getEnv()
}

export default tools
